⚡️ Speed up function _wrap_repr by 82%
#56
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 82% (0.82x) speedup for
_wrap_reprinxarray/datatree_/datatree/formatting_html.py⏱️ Runtime :
104 microseconds→57.1 microseconds(best of94runs)📝 Explanation and details
The optimized version achieves an 81% speedup by eliminating the expensive
"".join()operation on a 27-element list and replacing it with direct string concatenation using f-string formatting.Key optimizations applied:
Eliminated list construction and join: The original code created a 27-element list of string literals and then called
"".join()on it. The optimized version uses Python's automatic string literal concatenation within parentheses, which happens at compile time rather than runtime.Reduced string operations: Instead of 27 separate string objects being joined at runtime, the optimized version creates one large string template with only 2 variable interpolations (
heightandr).Minor conditional optimization: Changed
end is Falsetonot endfor slightly better performance.Why this leads to speedup:
"".join()on many small strings requires Python to iterate through the list, calculate total length, allocate a new string buffer, and copy each elementImpact on workloads:
Based on the function reference,
_wrap_repris called in a loop withinsummarize_children()for each child node in a data tree structure. This means the 81% speedup will be multiplied across potentially many child nodes, making tree rendering significantly faster. The test results show consistent 50-100% speedups across all test cases, with larger inputs still benefiting substantially (54-68% faster for large-scale tests).The optimization is particularly effective for this HTML templating use case where most of the output is static markup with only a few dynamic variables.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_wrap_repr-mio51b5mand push.